package com.fulizhe.catlocal.integration.resttemplate.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.dianping.cat.Cat;

@RestController
public class HelloController {

	@Autowired
	private ServerProperties sp;

	@Autowired
	private RestTemplate restTemplate;

	@GetMapping("/hello")
	public String index(HttpServletRequest request) {
		LoggerFactory.getLogger(this.getClass()).info("开始Spring RestTemplate调用....");

		httpTest();

		return String.format(
		      "<br><br> 当前请求的TraceId为 [ <strong> <a target=\"_blank\" href=\"./cat/cat.html?traceId=%s\">%s</a> </strong> ] <--- 点击左侧链接跳转到'CAT-LOCAL链路查询页面'查看链路日志 <br><br><br> %s", //
		      Cat.getCurrentMessageId(), Cat.getCurrentMessageId(),
		      "查看traceId来源, 请打开F12, 然后刷新页面, 在返回HTTP Header中有一个名为X-ROOT-TRACE-ID的key");
	}

	@GetMapping("/calledRemoteService")
	public String index2(HttpServletRequest request) {
		LoggerFactory.getLogger(this.getClass()).info("被Spring RestTemplate Invoke....");

		return "Invoked By Spring RestTemplate";
	}

	String httpTest() {
		final String url = String.format("http://127.0.0.1:%s/calledRemoteService", sp.getPort());

		ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

		String body = responseEntity.getBody();

		return body;
	}


}